Delete Node Without Head Pointer of the Linked List

Last updated: 8th Jan, 2021

        

Problem Statment

You are given a singly linked list and pointer which is pointing to the node which is required to be deleted. Any information about head pointer or any other node is not given. You need to write a function to delete that node from linked list. Your function will take only one argument: pointer to the node which is to be deleted.

Example 1:
Given a Linked List: [ 5 -> 2 -> 3 -> 8 ]
Input Format : 2 (a pointer to 2)
Output Format : [ 5 -> 3 -> 8 ]

Approach:

The trick here is we can copy the data of the next node to the data field of the current node to be deleted. Then we can move one step forward. Now our next has become the current node and current has become the previous node. Now we can easily delete the current node by conventional deletion methods.

C++ Code

#include <iostream>
using namespace std;
                            
class Node
{
    public:
    int data;
    Node *next;
    Node()          //default constructor   
    { }
    Node(int data)  //parameterized constructor
    {
        this -> data =data;
        next = NULL;
    }
};
                            
void display(Node *head)    //function to print the Linked List
{
    if(head == NULL)
        cout<<"\n List is Empty ";
    else
    {
        Node *temp = head;
        while(temp)
        {
            cout< data <<" ";
            temp = temp -> next;
        }
    }
}
//function for deletion without head pointer
void delete_value(Node *ele)
{                  
    if(ele == NULL)   //if Linked list is empty
        cout<<"\n List is Empty ";
    else if(ele -> next == NULL) //last node then can't be deleted
    {
        cout<<"\n Last node can't be deleted ";
    }
    else
    {
        ele -> data = ele -> next -> data;
        ele -> next = ele -> next -> next;
     }
}
                                                        
int main()
{
    // creating Linked List
    Node *n1 = new Node(5);
    n1 -> next = new Node(2);
    n1 -> next -> next = new Node(1);
    n1 -> next -> next -> next = new Node(3);
    cout<<"\n Before Deletion : ";
    display(n1);
                            
    //Node pointer to be deleted
    Node *del = n1 -> next;
    delete_value(del);
    cout<<"\n After deletion : ";
    display(n1);

    return 0;
}